package com.atguigu.bigdata.chapter11.function;

import com.atguigu.bigdata.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lzc
 * @Date 2022/9/9 14:09
 */
public class Flink03_Function_Agg {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("s1", 1000L, 10),
            new WaterSensor("s1", 2000L, 20),
            new WaterSensor("s1", 3000L, 30),
            new WaterSensor("s1", 4000L, 40),
            new WaterSensor("s2", 8000L, 80)
        );
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        Table table = tEnv.fromDataStream(stream, $("id"), $("ts"), $("vc"));
        tEnv.createTemporaryView("sensor", table);
        
        // 使用自定义函数有两种用法:
        // 1. 在table_api中使用
        // 1.1 内联用法
        
        // 1.2 先注册后使用
        tEnv.createTemporaryFunction("my_avg", MyAvg.class);
        
        /*table
            .groupBy($("id"))
            .select($("id"), call("my_avg", $("vc")))
            .execute()
            .print();*/
        
        // 2. 在sql中使用, 必须先注册函数
        tEnv.sqlQuery("select " +
                          "id, my_avg(vc) `avg` " +
                          "from sensor " +
                          "group by id ")
            .execute()
            .print();
        
        
    }
    
    public static class MyAvg extends AggregateFunction<Double, Avg> {
        
        // 初始化一个累加器
        @Override
        public Avg createAccumulator() {
            return new Avg();
        }
        
        // 就是返回最终的聚合结果
        @Override
        public Double getValue(Avg acc) {
            return acc.sum * 1.0 / acc.count;
        }
        
        // 累加过程的方法也是约定
        /*
        返回值必须是void
        方法名必须是: accumulate
        参数1: 必须是累加器, 把传入的参数用累加器进行累加
        参数2: 根据实际情况来定: 就传入的数据
         */
        public void accumulate(Avg acc, Integer vc){
            acc.sum += vc;
            acc.count++;
        }
        
        
    }
    
    
    public static class Avg {
        public Integer sum = 0;
        public Long count = 0L;
    }
    
}
/*
 
 */
